package com.hyfd.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.org.apache.bcel.internal.generic.RETURN;

public class PostUtil {
	private static final Logger logger = LoggerFactory.getLogger(PostUtil.class);
	/**
	 * 发送方法
	 * @param url
	 * @param message
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String httpPostWithJSON(String url, String message) throws ClientProtocolException, IOException {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		StringEntity entity = new StringEntity(message, "UTF-8");
		entity.setContentType("application/json;charset=UTF-8");
		httppost.setEntity(entity);
		httppost.addHeader("Accept", "application/json");
		httppost.addHeader("ContentType", "application/json;charset=UTF-8");

		HttpResponse response = httpclient.execute(httppost);
		try {
			int code = response.getStatusLine().getStatusCode();
			logger.error("code-->{}", code);
			if (HttpURLConnection.HTTP_OK == code) {
				String retMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
				return retMsg;
			}
		} catch (Exception e) {
			// TODO 请针对不同异常做相应的处理
			logger.error(e.getMessage(), e);
		} 
		return null;
	}
    
    /**
     * 接收
     * @param request
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
        
        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        String reqBody = sb.toString();
        return reqBody;
    }
}
